<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minecraft 3D Web Version - 六666qs 制作</title>
    <style>
        /* 基础样式 */
        body {
            margin: 0;
            overflow: hidden;
            background-color: #87CEEB;
            font-family: 'Minecraft', Arial, sans-serif;
        }
        canvas {
            display: block;
        }
        
        /* 开始页面样式 */
        #startScreen {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(to bottom, #3a6ea5 0%, #1e3d59 100%);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            color: white;
        }
        
        #startScreen h1 {
            font-size: 4rem;
            text-shadow: 4px 4px #000;
            margin-bottom: 1rem;
            color: #FFD700;
            letter-spacing: 2px;
        }
        
        .creator-name {
            font-size: 1.5rem;
            margin-bottom: 2rem;
            color: #FF6B6B;
            text-shadow: 2px 2px #000;
            font-weight: bold;
            background: rgba(0, 0, 0, 0.5);
            padding: 10px 20px;
            border-radius: 10px;
            border: 2px solid #FFD700;
        }
        
        .start-button {
            background: linear-gradient(to bottom, #8B8B8B 0%, #5A5A5A 100%);
            border: 4px solid #373737;
            color: white;
            padding: 15px 40px;
            font-size: 1.5rem;
            margin: 10px;
            cursor: pointer;
            text-shadow: 2px 2px #000;
            box-shadow: 0 6px #2A2A2A;
            transition: all 0.1s;
            border-radius: 8px;
            font-family: 'Minecraft', Arial, sans-serif;
        }
        
        .start-button:hover {
            background: linear-gradient(to bottom, #9B9B9B 0%, #6A6A6A 100%);
            transform: translateY(-2px);
        }
        
        .start-button:active {
            box-shadow: 0 2px #2A2A2A;
            transform: translateY(4px);
        }
        
        .start-button.multiplayer {
            background: linear-gradient(to bottom, #3CB371 0%, #2E8B57 100%);
            border-color: #2A7A4A;
            box-shadow: 0 6px #1E5A35;
        }
        
        .start-button.multiplayer:hover {
            background: linear-gradient(to bottom, #4CC381 0%, #3E9B67 100%);
        }
        
        .start-button.multiplayer:active {
            box-shadow: 0 2px #1E5A35;
        }
        
        .start-button.options {
            background: linear-gradient(to bottom, #808080 0%, #606060 100%);
            border-color: #505050;
            box-shadow: 0 6px #404040;
        }
        
        .start-button.options:hover {
            background: linear-gradient(to bottom, #909090 0%, #707070 100%);
        }
        
        .start-button.options:active {
            box-shadow: 0 2px #404040;
        }
        
        #versionInfo {
            position: absolute;
            bottom: 10px;
            right: 10px;
            color: #DDD;
            font-size: 0.8rem;
        }
        
        /* 加载页面样式 */
        #loadingScreen {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: #1e3d59;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 999;
            color: white;
            display: none;
        }
        
        #loadingScreen h2 {
            font-size: 2.5rem;
            margin-bottom: 2rem;
            color: #FFD700;
            text-shadow: 2px 2px #000;
        }
        
        .loading-bar {
            width: 300px;
            height: 20px;
            background-color: #2A2A2A;
            border: 2px solid #000;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 1rem;
        }
        
        .loading-progress {
            height: 100%;
            width: 0%;
            background: linear-gradient(to right, #3CB371, #FFD700);
            transition: width 0.3s;
        }
        
        #loadingText {
            font-size: 1.2rem;
            margin-top: 1rem;
        }
        
        /* 游戏内UI样式 */
        #info {
            position: absolute;
            top: 10px;
            left: 10px;
            color: white;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 10px;
            border-radius: 5px;
            font-size: 14px;
            z-index: 100;
            display: none;
            max-width: 300px;
        }
        
        .creator-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            color: white;
            background: linear-gradient(135deg, #FF6B6B, #FFD700);
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 14px;
            z-index: 100;
            display: none;
            font-weight: bold;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
            border: 2px solid white;
        }
        
        #controls {
            position: absolute;
            bottom: 10px;
            left: 10px;
            color: white;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 10px;
            border-radius: 5px;
            z-index: 100;
            display: none;
        }
        
        #inventory {
            position: absolute;
            top: 10px;
            right: 10px;
            color: white;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 5px;
            width: 300px;
            max-height: 80vh;
            overflow-y: auto;
            z-index: 100;
            display: none;
        }
        
        #multiplayer {
            position: absolute;
            bottom: 10px;
            right: 10px;
            color: white;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 5px;
            width: 300px;
            max-height: 80vh;
            overflow-y: auto;
            z-index: 100;
            display: none;
        }
        
        .block-item {
            display: inline-block;
            width: 50px;
            height: 50px;
            margin: 5px;
            text-align: center;
            cursor: pointer;
            border: 2px solid transparent;
            border-radius: 5px;
            padding: 5px;
        }
        
        .block-item:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .block-item.selected {
            border-color: #4CAF50;
            background-color: rgba(76, 175, 80, 0.3);
        }
        
        .category {
            margin-bottom: 15px;
        }
        
        .category-title {
            font-weight: bold;
            margin-bottom: 5px;
            color: #4CAF50;
        }
        
        button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 8px 15px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        input[type="text"] {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .player-list {
            max-height: 150px;
            overflow-y: auto;
            margin-top: 10px;
        }
        
        .player-item {
            padding: 5px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        @font-face {
            font-family: 'Minecraft';
            src: url('https://assets.mojang.com/fonts/minecraft.woff2') format('woff2');
        }
        
        .hud {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 5px;
            z-index: 100;
            display: none;
        }
        
        .hotbar-slot {
            width: 50px;
            height: 50px;
            background-color: rgba(0, 0, 0, 0.5);
            border: 2px solid #555;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .hotbar-slot.selected {
            border-color: #4CAF50;
            background-color: rgba(76, 175, 80, 0.3);
        }
        
        .server-option {
            margin: 10px 0;
            padding: 10px;
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 5px;
            cursor: pointer;
        }
        
        .server-option:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .server-option.selected {
            border: 2px solid #4CAF50;
        }
        
        .server-list {
            max-height: 200px;
            overflow-y: auto;
            margin-top: 10px;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            #startScreen h1 {
                font-size: 2.5rem;
            }
            
            .creator-name {
                font-size: 1.2rem;
                padding: 8px 15px;
            }
            
            .start-button {
                font-size: 1.2rem;
                padding: 12px 30px;
            }
            
            .hud {
                bottom: 10px;
            }
            
            .hotbar-slot {
                width: 40px;
                height: 40px;
            }
            
            #info, #controls, #inventory, #multiplayer {
                font-size: 12px;
                padding: 8px;
            }
            
            .creator-badge {
                font-size: 12px;
                padding: 6px 12px;
            }
        }
    </style>
</head>
<body>
    <!-- 开始页面 -->
    <div id="startScreen">
        <h1>MINECRAFT</h1>
        <div class="creator-name">创作者: 六666qs</div>
        <button class="start-button" id="singleplayerBtn">单人游戏</button>
        <button class="start-button multiplayer" id="multiplayerBtn">多人游戏</button>
        <button class="start-button options" id="optionsBtn">选项</button>
        <div id="versionInfo">Minecraft Web Edition v1.0 | 六666qs 制作</div>
    </div>
    
    <!-- 加载页面 -->
    <div id="loadingScreen">
        <h2>加载中...</h2>
        <div class="loading-bar">
            <div class="loading-progress" id="loadingProgress"></div>
        </div>
        <div id="loadingText">正在生成世界...</div>
    </div>
    
    <!-- 游戏内UI -->
    <div id="info">
        Minecraft 3D Web Version - Enhanced<br/>
        创作者: 六666qs<br/>
        WASD: 移动 | 鼠标: 视角 | 空格: 跳跃<br/>
        E: 打开背包 | M: 多人游戏 | 1-9: 快捷栏选择<br/>
        左键: 放置方块 | 右键: 移除方块
    </div>
    
    <div class="creator-badge">创作者: 六666qs</div>
    
    <div class="hud">
        <!-- 快捷栏将由JavaScript动态生成 -->
    </div>
    
    <div id="controls">
        <button id="toggleInventory">打开背包 (E)</button>
        <button id="toggleMultiplayer">多人游戏 (M)</button>
        <button id="resetScene">重置场景</button>
        <button id="backToMenu">返回主菜单</button>
    </div>
    
    <div id="inventory">
        <h3>背包 - 六666qs 制作</h3>
        <div class="category">
            <div class="category-title">自然方块</div>
            <div id="natural-blocks" class="block-list"></div>
        </div>
        <div class="category">
            <div class="category-title">建筑方块</div>
            <div id="building-blocks" class="block-list"></div>
        </div>
        <div class="category">
            <div class="category-title">装饰方块</div>
            <div id="decorative-blocks" class="block-list"></div>
        </div>
        <div class="category">
            <div class="category-title">工具</div>
            <div id="tools" class="block-list"></div>
        </div>
        <button id="closeInventory" style="width:100%; margin-top:10px;">关闭背包</button>
    </div>
    
    <div id="multiplayer">
        <h3>多人游戏 - 六666qs 制作</h3>
        
        <div class="server-option" id="localServerOption">
            <strong>局域网服务器</strong><br/>
            <small>连接到本地网络中的服务器</small>
        </div>
        
        <div class="server-option" id="officialServerOption">
            <strong>官方服务器</strong><br/>
            <small>连接到公共游戏服务器</small>
        </div>
        
        <div id="serverConfig">
            <input type="text" id="serverAddress" placeholder="服务器地址 (例如: ws://localhost:8080)">
            <button id="connectServer">连接服务器</button>
            <button id="disconnectServer" disabled>断开连接</button>
        </div>
        
        <div>
            <input type="text" id="playerName" placeholder="玩家名称">
            <button id="setPlayerName">设置名称</button>
        </div>
        
        <div class="server-list" id="officialServerList">
            <h4>官方服务器列表 (50个)</h4>
            <!-- 服务器列表将由JavaScript动态生成 -->
        </div>
        
        <div class="player-list" id="playerList">
            <div>玩家列表:</div>
        </div>
        
        <button id="closeMultiplayer" style="width:100%; margin-top:10px;">关闭</button>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.min.js"></script>

    <script>
        // 初始化场景、相机和渲染器
        let scene, camera, renderer, controls, raycaster, mouse;
        let blocks = []; // 存储所有方块的数组
        
        // 方块定义
        const blockTypes = {
            // 自然方块
            grass: { name: '草方块', category: 'natural', color: '#7CFC00' },
            dirt: { name: '泥土', category: 'natural', color: '#8B4513' },
            stone: { name: '石头', category: 'natural', color: '#808080' },
            sand: { name: '沙子', category: 'natural', color: '#F4A460' },
            water: { name: '水', category: 'natural', color: '#1E90FF' },
            leaves: { name: '树叶', category: 'natural', color: '#228B22' },
            
            // 建筑方块
            wood: { name: '木头', category: 'building', color: '#DEB887' },
            brick: { name: '砖块', category: 'building', color: '#B22222' },
            cobblestone: { name: '圆石', category: 'building', color: '#696969' },
            glass: { name: '玻璃', category: 'building', color: '#F0F8FF' },
            
            // 矿石
            coal_ore: { name: '煤矿石', category: 'ores', color: '#2F4F4F' },
            iron_ore: { name: '铁矿石', category: 'ores', color: '#D3D3D3' },
            gold_ore: { name: '金矿石', category: 'ores', color: '#FFD700' },
            diamond_ore: { name: '钻石矿石', category: 'ores', color: '#00BFFF' },
            
            // 工具
            pickaxe: { name: '镐', category: 'tools', color: '#A9A9A9' },
            axe: { name: '斧', category: 'tools', color: '#A9A9A9' },
            shovel: { name: '锹', category: 'tools', color: '#A9A9A9' }
        };

        // 当前选中的方块类型和快捷栏
        let currentBlockType = 'grass';
        let hotbarSlots = ['grass', 'dirt', 'stone', 'wood', 'sand', 'glass', 'brick', 'cobblestone', 'water'];
        let selectedHotbarSlot = 0;

        // 玩家数据
        let playerName = 'Player' + Math.floor(Math.random() * 1000);
        let players = {};
        let websocket = null;
        let serverType = 'local'; // 服务器类型: local 或 official

        // 预定义的服务器列表 - 50个官方服务器
        const servers = {
            local: [
                { name: '本地服务器1', address: 'ws://localhost:8080' },
                { name: '本地服务器2', address: 'ws://192.168.1.100:8080' }
            ],
            official: [
                { name: 'Hypixel Network', address: 'wss://mc.hypixel.net', players: 50000, ping: 20 },
                { name: 'Mineplex', address: 'wss://us.mineplex.com', players: 25000, ping: 30 },
                { name: 'The Hive', address: 'wss://play.hivemc.com', players: 15000, ping: 25 },
                { name: 'Cubecraft Games', address: 'wss://play.cubecraft.net', players: 12000, ping: 40 },
                { name: 'Mineville City', address: 'wss://play.inpvp.net', players: 8000, ping: 35 },
                { name: 'Lifeboat Network', address: 'wss://lb.mineplex.com', players: 7000, ping: 50 },
                { name: 'GommeHD.net', address: 'wss://gommehd.net', players: 6000, ping: 45 },
                { name: 'MineSuperior', address: 'wss://play.mcs.gg', players: 5500, ping: 60 },
                { name: 'JartexNetwork', address: 'wss://jartexnetwork.com', players: 5000, ping: 55 },
                { name: 'BlocksMC', address: 'wss://blocksmc.com', players: 4800, ping: 65 },
                { name: 'PikaNetwork', address: 'wss://play.pika-network.net', players: 4500, ping: 70 },
                { name: 'MineHeroes', address: 'wss://mineheroes.org', players: 4200, ping: 75 },
                { name: 'VortexNetwork', address: 'wss://vortexnetwork.net', players: 4000, ping: 80 },
                { name: 'GalaxyMC', address: 'wss://galaxymc.eu', players: 3800, ping: 85 },
                { name: 'MineLand', address: 'wss://mineland.net', players: 3500, ping: 90 },
                { name: 'PixelmonCraft', address: 'wss://pixelmoncraft.com', players: 3200, ping: 95 },
                { name: 'MineYourMind', address: 'wss://mineyourmind.net', players: 3000, ping: 100 },
                { name: 'Purple Prison', address: 'wss://purpleprison.net', players: 2800, ping: 105 },
                { name: 'MineArcade', address: 'wss://minearcade.net', players: 2600, ping: 110 },
                { name: 'Faithful MC', address: 'wss://faithfulmc.net', players: 2400, ping: 115 },
                { name: 'MineHQ', address: 'wss://minehq.com', players: 2200, ping: 120 },
                { name: 'MineWind', address: 'wss://minewind.com', players: 2000, ping: 125 },
                { name: 'Mineverse', address: 'wss://mineverse.com', players: 1800, ping: 130 },
                { name: 'MineFortress', address: 'wss://minefortress.com', players: 1600, ping: 135 },
                { name: 'MineFantasy', address: 'wss://minefantasy.com', players: 1400, ping: 140 },
                { name: 'MineAdventure', address: 'wss://mineadventure.com', players: 1200, ping: 145 },
                { name: 'MineCrafters', address: 'wss://minecrafters.com', players: 1000, ping: 150 },
                { name: 'MineKingdom', address: 'wss://minekingdom.com', players: 900, ping: 155 },
                { name: 'MineEmpire', address: 'wss://mineempire.com', players: 800, ping: 160 },
                { name: 'MineLegends', address: 'wss://minelegends.com', players: 700, ping: 165 },
                { name: 'MineUniverse', address: 'wss://mineuniverse.com', players: 600, ping: 170 },
                { name: 'MineGalaxy', address: 'wss://minegalaxy.com', players: 550, ping: 175 },
                { name: 'MineWorld', address: 'wss://mineworld.com', players: 500, ping: 180 },
                { name: 'MineRealm', address: 'wss://minerealm.com', players: 450, ping: 185 },
                { name: 'MineDimension', address: 'wss://minedimension.com', players: 400, ping: 190 },
                { name: 'MineHorizon', address: 'wss://minehorizon.com', players: 350, ping: 195 },
                { name: 'MineFrontier', address: 'wss://minefrontier.com', players: 300, ping: 200 },
                { name: 'MineOdyssey', address: 'wss://mineodyssey.com', players: 280, ping: 205 },
                { name: 'MineExpedition', address: 'wss://mineexpedition.com', players: 260, ping: 210 },
                { name: 'MineQuest', address: 'wss://minequest.com', players: 240, ping: 215 },
                { name: 'MineVoyage', address: 'wss://minevoyage.com', players: 220, ping: 220 },
                { name: 'MineExplorers', address: 'wss://mineexplorers.com', players: 200, ping: 225 },
                { name: 'MinePioneers', address: 'wss://minepioneers.com', players: 180, ping: 230 },
                { name: 'MineSettlers', address: 'wss://minesettlers.com', players: 160, ping: 235 },
                { name: 'MineColonists', address: 'wss://minecolonists.com', players: 140, ping: 240 },
                { name: 'MineBuilders', address: 'wss://minebuilders.com', players: 120, ping: 245 },
                { name: 'MineArchitects', address: 'wss://minearchitects.com', players: 100, ping: 250 },
                { name: 'MineEngineers', address: 'wss://mineengineers.com', players: 80, ping: 255 },
                { name: 'MineCraftsmen', address: 'wss://minecraftsmen.com', players: 60, ping: 260 },
                { name: 'MineArtisans', address: 'wss://mineartisans.com', players: 40, ping: 265 }
            ]
        };

        // 初始化UI
        function initUI() {
            // 创建快捷栏
            const hud = document.querySelector('.hud');
            hud.innerHTML = '';
            
            for (let i = 0; i < 9; i++) {
                const slot = document.createElement('div');
                slot.className = i === selectedHotbarSlot ? 'hotbar-slot selected' : 'hotbar-slot';
                slot.innerHTML = `<div style="width:40px;height:40px;background-color:${blockTypes[hotbarSlots[i]].color};"></div>`;
                slot.addEventListener('click', () => selectHotbarSlot(i));
                hud.appendChild(slot);
            }
            
            // 初始化背包
            initInventory();
            
            // 设置玩家名称
            document.getElementById('playerName').value = playerName;
            
            // 初始化服务器选择
            initServerSelection();
        }

        // 初始化服务器选择
        function initServerSelection() {
            const localOption = document.getElementById('localServerOption');
            const officialOption = document.getElementById('officialServerOption');
            
            localOption.addEventListener('click', () => {
                serverType = 'local';
                localOption.classList.add('selected');
                officialOption.classList.remove('selected');
                updateServerList();
            });
            
            officialOption.addEventListener('click', () => {
                serverType = 'official';
                officialOption.classList.add('selected');
                localOption.classList.remove('selected');
                updateServerList();
            });
            
            // 默认选择局域网
            localOption.click();
        }

        // 更新服务器列表
        function updateServerList() {
            const serverList = document.getElementById('officialServerList');
            serverList.innerHTML = '<h4>官方服务器列表 (50个)</h4>';
            
            servers.official.forEach(server => {
                const serverItem = document.createElement('div');
                serverItem.className = 'server-option';
                serverItem.innerHTML = `
                    <strong>${server.name}</strong><br/>
                    <small>地址: ${server.address}</small><br/>
                    <small>在线玩家: ${server.players} | 延迟: ${server.ping}ms</small>
                `;
                serverItem.addEventListener('click', () => {
                    document.getElementById('serverAddress').value = server.address;
                });
                serverList.appendChild(serverItem);
            });
        }

        // 初始化背包
        function initInventory() {
            const naturalBlocks = document.getElementById('natural-blocks');
            const buildingBlocks = document.getElementById('building-blocks');
            const decorativeBlocks = document.getElementById('decorative-blocks');
            const tools = document.getElementById('tools');
            
            naturalBlocks.innerHTML = '';
            buildingBlocks.innerHTML = '';
            decorativeBlocks.innerHTML = '';
            tools.innerHTML = '';
            
            Object.keys(blockTypes).forEach(blockId => {
                const block = blockTypes[blockId];
                const blockItem = document.createElement('div');
                blockItem.className = 'block-item';
                blockItem.innerHTML = `
                    <div style="width:40px;height:40px;background-color:${block.color};margin:0 auto;"></div>
                    <div style="font-size:10px;">${block.name}</div>
                `;
                blockItem.addEventListener('click', () => {
                    // 从背包选择方块时，同时更新快捷栏
                    currentBlockType = blockId;
                    
                    // 如果方块不在快捷栏中，添加到当前选中的快捷栏槽位
                    if (!hotbarSlots.includes(blockId)) {
                        hotbarSlots[selectedHotbarSlot] = blockId;
                        updateHotbar();
                    }
                    
                    updateSelectedBlock();
                });
                
                switch(block.category) {
                    case 'natural':
                        naturalBlocks.appendChild(blockItem);
                        break;
                    case 'building':
                        buildingBlocks.appendChild(blockItem);
                        break;
                    case 'ores':
                        decorativeBlocks.appendChild(blockItem);
                        break;
                    case 'tools':
                        tools.appendChild(blockItem);
                        break;
                }
            });
        }

        // 更新快捷栏显示
        function updateHotbar() {
            const hud = document.querySelector('.hud');
            hud.innerHTML = '';
            
            for (let i = 0; i < 9; i++) {
                const slot = document.createElement('div');
                slot.className = i === selectedHotbarSlot ? 'hotbar-slot selected' : 'hotbar-slot';
                slot.innerHTML = `<div style="width:40px;height:40px;background-color:${blockTypes[hotbarSlots[i]].color};"></div>`;
                slot.addEventListener('click', () => selectHotbarSlot(i));
                hud.appendChild(slot);
            }
        }

        // 更新选中的方块
        function updateSelectedBlock() {
            // 更新背包中的选中状态
            document.querySelectorAll('.block-item').forEach(item => {
                const blockColor = item.querySelector('div').style.backgroundColor;
                const blockType = Object.keys(blockTypes).find(type => 
                    blockTypes[type].color === blockColor.replace(/\s/g, '')
                );
                item.classList.toggle('selected', blockType === currentBlockType);
            });
            
            // 更新快捷栏中的选中状态
            document.querySelectorAll('.hotbar-slot').forEach((slot, index) => {
                slot.classList.toggle('selected', index === selectedHotbarSlot);
            });
        }

        // 选择快捷栏槽位
        function selectHotbarSlot(index) {
            selectedHotbarSlot = index;
            currentBlockType = hotbarSlots[index];
            updateSelectedBlock();
        }

        // 创建方块函数 - 修复bug
        function createBlock(type, x, y, z) {
            // 检查位置是否已有方块
            const existingBlock = blocks.find(block => 
                Math.abs(block.position.x - x) < 0.1 &&
                Math.abs(block.position.y - y) < 0.1 &&
                Math.abs(block.position.z - z) < 0.1
            );
            
            if (existingBlock) {
                return null; // 位置已有方块，不创建
            }
            
            const geometry = new THREE.BoxGeometry(1, 1, 1);
            const material = new THREE.MeshBasicMaterial({ 
                color: blockTypes[type].color,
                transparent: type === 'water' || type === 'glass',
                opacity: type === 'water' ? 0.7 : type === 'glass' ? 0.9 : 1
            });
            
            const cube = new THREE.Mesh(geometry, material);
            cube.position.set(x, y, z);
            cube.userData = { type: type, id: Date.now() + Math.random() };
            
            scene.add(cube);
            blocks.push(cube);
            return cube;
        }

        // 移除方块函数 - 修复bug
        function removeBlock(x, y, z) {
            const blockIndex = blocks.findIndex(block => 
                Math.abs(block.position.x - x) < 0.1 &&
                Math.abs(block.position.y - y) < 0.1 &&
                Math.abs(block.position.z - z) < 0.1
            );
            
            if (blockIndex !== -1) {
                const block = blocks[blockIndex];
                scene.remove(block);
                blocks.splice(blockIndex, 1);
                
                // 如果是多人游戏，发送方块移除消息
                if (websocket && websocket.readyState === WebSocket.OPEN) {
                    websocket.send(JSON.stringify({
                        type: 'block_remove',
                        x: x,
                        y: y,
                        z: z,
                        player: playerName
                    }));
                }
                
                return true; // 成功移除方块
            }
            
            return false; // 未找到方块
        }

        // 添加一些初始方块
        function createInitialBlocks() {
            createBlock('grass', 0, 0, 0);
            createBlock('dirt', 1, 0, 0);
            createBlock('stone', 0, 0, 1);
            createBlock('wood', -1, 0, 0);
            createBlock('sand', 2, 0, 0);
            createBlock('glass', 0, 0, 2);
            createBlock('brick', -2, 0, 0);
            createBlock('cobblestone', 0, 0, -1);
            createBlock('water', 1, 0, 1);
        }

        // 初始化游戏
        function initGame() {
            // 创建场景
            scene = new THREE.Scene();
            
            // 创建相机
            camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            camera.position.set(5, 5, 5);
            camera.lookAt(0, 0, 0);
            
            // 创建渲染器
            renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setClearColor(0x87CEEB);
            document.body.appendChild(renderer.domElement);

            // 添加光源
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
            scene.add(ambientLight);
            
            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
            directionalLight.position.set(1, 1, 1);
            scene.add(directionalLight);

            // 添加网格地面
            const gridHelper = new THREE.GridHelper(100, 100);
            scene.add(gridHelper);

            // 添加轨道控制器
            controls = new THREE.OrbitControls(camera, renderer.domElement);
            controls.enableDamping = true;
            controls.dampingFactor = 0.05;

            // 初始化射线投射器
            raycaster = new THREE.Raycaster();
            mouse = new THREE.Vector2();

            // 初始化UI
            initUI();
            
            // 创建初始方块
            createInitialBlocks();
            
            // 显示游戏UI
            document.getElementById('info').style.display = 'block';
            document.querySelector('.creator-badge').style.display = 'block';
            document.getElementById('controls').style.display = 'block';
            document.querySelector('.hud').style.display = 'flex';
        }

        // 鼠标点击交互
        function onMouseClick(event) {
            // 如果UI打开，不处理点击
            if (document.getElementById('inventory').style.display === 'block' || 
                document.getElementById('multiplayer').style.display === 'block') {
                return;
            }
            
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
            
            raycaster.setFromCamera(mouse, camera);
            
            // 只检测方块，不检测地面网格
            const intersects = raycaster.intersectObjects(blocks);
            
            if (intersects.length > 0) {
                const intersect = intersects[0];
                
                if (event.button === 0) { // 左键放置方块
                    const normal = intersect.face.normal;
                    const newPosition = intersect.object.position.clone().add(normal);
                    const newBlock = createBlock(currentBlockType, newPosition.x, newPosition.y, newPosition.z);
                    
                    if (newBlock) {
                        // 如果是多人游戏，发送方块放置消息
                        if (websocket && websocket.readyState === WebSocket.OPEN) {
                            websocket.send(JSON.stringify({
                                type: 'block_place',
                                blockType: currentBlockType,
                                x: newPosition.x,
                                y: newPosition.y,
                                z: newPosition.z,
                                player: playerName
                            }));
                        }
                    }
                } else if (event.button === 2) { // 右键移除方块
                    removeBlock(
                        intersect.object.position.x,
                        intersect.object.position.y,
                        intersect.object.position.z
                    );
                }
            }
        }

        // 键盘控制
        const keys = {};
        
        function handleKeyDown(event) {
            keys[event.code] = true;
            
            // 快捷栏选择
            if (event.code >= 'Digit1' && event.code <= 'Digit9') {
                const slotIndex = parseInt(event.code[5]) - 1;
                selectHotbarSlot(slotIndex);
            }
            
            // 打开背包
            if (event.code === 'KeyE') {
                toggleInventory();
                event.preventDefault();
            }
            
            // 打开多人游戏
            if (event.code === 'KeyM') {
                toggleMultiplayer();
                event.preventDefault();
            }
        }
        
        function handleKeyUp(event) {
            keys[event.code] = false;
        }

        // 切换背包显示
        function toggleInventory() {
            const inventory = document.getElementById('inventory');
            inventory.style.display = inventory.style.display === 'block' ? 'none' : 'block';
        }

        // 切换多人游戏显示
        function toggleMultiplayer() {
            const multiplayer = document.getElementById('multiplayer');
            multiplayer.style.display = multiplayer.style.display === 'block' ? 'none' : 'block';
        }

        // 连接WebSocket服务器
        function connectToServer() {
            const serverAddress = document.getElementById('serverAddress').value;
            if (!serverAddress) {
                alert('请输入服务器地址');
                return;
            }
            
            try {
                websocket = new WebSocket(serverAddress);
                
                websocket.onopen = () => {
                    console.log('连接到服务器');
                    document.getElementById('connectServer').disabled = true;
                    document.getElementById('disconnectServer').disabled = false;
                    
                    // 发送玩家加入消息
                    websocket.send(JSON.stringify({
                        type: 'player_join',
                        player: playerName
                    }));
                };
                
                websocket.onmessage = (event) => {
                    const message = JSON.parse(event.data);
                    handleServerMessage(message);
                };
                
                websocket.onclose = () => {
                    console.log('与服务器断开连接');
                    document.getElementById('connectServer').disabled = false;
                    document.getElementById('disconnectServer').disabled = true;
                    players = {};
                    updatePlayerList([]);
                };
                
                websocket.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    alert('连接服务器失败');
                };
                
            } catch (error) {
                console.error('连接错误:', error);
                alert('连接服务器失败');
            }
        }

        // 处理服务器消息
        function handleServerMessage(message) {
            switch (message.type) {
                case 'player_list':
                    updatePlayerList(message.players);
                    break;
                case 'block_place':
                    // 其他玩家放置方块
                    createBlock(message.blockType, message.x, message.y, message.z);
                    break;
                case 'block_remove':
                    // 其他玩家移除方块
                    removeBlock(message.x, message.y, message.z);
                    break;
                case 'player_join':
                    players[message.player] = true;
                    updatePlayerList(Object.keys(players));
                    break;
                case 'player_leave':
                    delete players[message.player];
                    updatePlayerList(Object.keys(players));
                    break;
                case 'world_data':
                    // 服务器发送世界数据
                    loadWorldData(message.blocks);
                    break;
            }
        }

        // 加载世界数据
        function loadWorldData(blockData) {
            // 清除现有方块
            blocks.forEach(block => scene.remove(block));
            blocks = [];
            
            // 创建新方块
            blockData.forEach(block => {
                createBlock(block.type, block.x, block.y, block.z);
            });
        }

        // 更新玩家列表
        function updatePlayerList(playerNames) {
            const playerList = document.getElementById('playerList');
            playerList.innerHTML = '<div>玩家列表:</div>';
            
            playerNames.forEach(player => {
                const playerItem = document.createElement('div');
                playerItem.className = 'player-item';
                playerItem.textContent = player;
                playerList.appendChild(playerItem);
            });
        }

        // 窗口大小调整
        function handleResize() {
            if (camera && renderer) {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            }
        }

        // 模拟加载过程
        function simulateLoading() {
            const loadingScreen = document.getElementById('loadingScreen');
            const loadingProgress = document.getElementById('loadingProgress');
            const loadingText = document.getElementById('loadingText');
            
            loadingScreen.style.display = 'flex';
            
            let progress = 0;
            const loadingSteps = [
                '正在生成世界...',
                '加载方块纹理...',
                '初始化游戏引擎...',
                '准备渲染系统...',
                '加载玩家数据...',
                '完成加载!'
            ];
            
            const interval = setInterval(() => {
                progress += Math.random() * 10;
                if (progress > 100) progress = 100;
                
                loadingProgress.style.width = progress + '%';
                loadingText.textContent = loadingSteps[Math.floor(progress / 20)] || loadingSteps[loadingSteps.length - 1];
                
                if (progress >= 100) {
                    clearInterval(interval);
                    
                    // 延迟显示游戏内容
                    setTimeout(() => {
                        loadingScreen.style.display = 'none';
                        initGame();
                        startGameLoop();
                    }, 500);
                }
            }, 200);
        }

        // 开始游戏循环
        function startGameLoop() {
            // 添加事件监听器
            window.addEventListener('mousedown', onMouseClick, false);
            window.addEventListener('keydown', handleKeyDown);
            window.addEventListener('keyup', handleKeyUp);
            window.addEventListener('resize', handleResize);
            
            // 阻止右键菜单
            window.addEventListener('contextmenu', (event) => {
                if (document.getElementById('inventory').style.display !== 'block' && 
                    document.getElementById('multiplayer').style.display !== 'block') {
                    event.preventDefault();
                }
            });
            
            // 动画循环
            function animate() {
                requestAnimationFrame(animate);
                
                // 简单的WASD移动
                if (keys['KeyW']) {
                    camera.position.z -= 0.1;
                }
                if (keys['KeyS']) {
                    camera.position.z += 0.1;
                }
                if (keys['KeyA']) {
                    camera.position.x -= 0.1;
                }
                if (keys['KeyD']) {
                    camera.position.x += 0.1;
                }
                if (keys['Space']) {
                    camera.position.y += 0.1;
                }
                if (keys['ShiftLeft']) {
                    camera.position.y -= 0.1;
                }
                
                if (controls) {
                    controls.update();
                }
                
                if (scene && camera) {
                    renderer.render(scene, camera);
                }
            }
            animate();
        }

        // 返回主菜单
        function backToMenu() {
            // 清除游戏状态
            if (scene) {
                scene.children.forEach(child => scene.remove(child));
            }
            
            if (renderer) {
                document.body.removeChild(renderer.domElement);
            }
            
            // 移除事件监听器
            window.removeEventListener('mousedown', onMouseClick);
            window.removeEventListener('keydown', handleKeyDown);
            window.removeEventListener('keyup', handleKeyUp);
            window.removeEventListener('resize', handleResize);
            
            // 重置变量
            scene = null;
            camera = null;
            renderer = null;
            controls = null;
            blocks = [];
            
            // 隐藏游戏UI
            document.getElementById('info').style.display = 'none';
            document.querySelector('.creator-badge').style.display = 'none';
            document.getElementById('controls').style.display = 'none';
            document.querySelector('.hud').style.display = 'none';
            document.getElementById('inventory').style.display = 'none';
            document.getElementById('multiplayer').style.display = 'none';
            
            // 显示开始页面
            document.getElementById('startScreen').style.display = 'flex';
        }

        // 初始化事件监听器
        function initEventListeners() {
            // 开始页面按钮
            document.getElementById('singleplayerBtn').addEventListener('click', () => {
                document.getElementById('startScreen').style.display = 'none';
                simulateLoading();
            });
            
            document.getElementById('multiplayerBtn').addEventListener('click', () => {
                document.getElementById('startScreen').style.display = 'none';
                simulateLoading();
                // 模拟加载完成后自动打开多人游戏界面
                setTimeout(() => {
                    toggleMultiplayer();
                }, 1500);
            });
            
            document.getElementById('optionsBtn').addEventListener('click', () => {
                alert('选项功能正在开发中...');
            });
            
            // 游戏内UI按钮
            document.getElementById('toggleInventory').addEventListener('click', toggleInventory);
            document.getElementById('toggleMultiplayer').addEventListener('click', toggleMultiplayer);
            document.getElementById('closeInventory').addEventListener('click', toggleInventory);
            document.getElementById('closeMultiplayer').addEventListener('click', toggleMultiplayer);
            document.getElementById('connectServer').addEventListener('click', connectToServer);
            document.getElementById('disconnectServer').addEventListener('click', () => {
                if (websocket) {
                    websocket.close();
                }
            });
            document.getElementById('setPlayerName').addEventListener('click', () => {
                const newName = document.getElementById('playerName').value;
                if (newName) {
                    playerName = newName;
                    alert('玩家名称已更新: ' + playerName);
                }
            });
            document.getElementById('resetScene').addEventListener('click', () => {
                // 移除所有方块
                blocks.forEach(block => scene.remove(block));
                blocks = [];
                
                // 重新添加初始方块
                createInitialBlocks();
            });
            document.getElementById('backToMenu').addEventListener('click', backToMenu);
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            initEventListeners();
            updateServerList(); // 初始化服务器列表
        });
    </script>
</body>
</html>